<?php
require_once("taskView.php");
require_once(CORE_DIR.'taskModel.php');
require_once(CORE_DIR.'taskpointModel.php');

class addAction extends authAction{

	function __construct(){
		$this->view = new taskView();
	}

	public function run($get, $post, $viewtype) {
		parent::run($get,$post,$viewtype);
		
		$tpModel = new taskpointModel();	
		$tModel = new taskModel();	 	
		
		if (isset($get["title"])){
			$tskName = htmlspecialchars($get["title"], ENT_QUOTES);
			$tskDesc = htmlspecialchars($get["desc"], ENT_QUOTES);
			$tskStatus = $get["state"];
			$tskImportant = $get["important"];
			$tskType = $get["tasktype"];
			$tskSplit = $get["tasksplit"];
			$tskFinishDate = $get["taskfinishdate"];
			
			$pid = $get['pid'];
			
			$ownerId = $get["ownerid"];
			$uids = (isset($get["uids"]) && $get["uids"]!="") ? explode("|", $get["uids"]) : array();
			$uids = array_merge((array)$uids, (array)$ownerId);
			
			if ($tskSplit == '1'){
				for ($i = 0; $i < count($uids); $i++){
					$lastInsertId = $tModel->addTask($pid, $tskName, $tskDesc, $tskImportant, $tskType, $tskStatus, $tskFinishDate);
					$status = 0;
					$id = 0;

					if (isset($get["pointtypeid"]) && isset($get["point"])){
						$tpModel->addTaskPoint($get["pointtypeid"], $lastInsertId, $get["point"]);
					}

					if ($lastInsertId > 0){
						$status = 1;
						$id = $lastInsertId;
						$tModel->addUserToTask($id, $uids[$i]);
					}
				}	
			}
			else{
				$lastInsertId = $tModel->addTask($pid, $tskName, $tskDesc, $tskImportant, $tskType, $tskStatus, $tskFinishDate);
				$status = 0;
				$id = 0;

				if (isset($get["pointtypeid"]) && isset($get["point"])){
					$tpModel->addTaskPoint($get["pointtypeid"], $lastInsertId, $get["point"]);
				}
			
				if ($lastInsertId > 0){
					$status = 1;
					$id = $lastInsertId;
					$tModel->addUsersToTask($id, $uids, $ownerId);
				}
			}

			$this->view->setProperty("status", $status);
			$this->view->setProperty("id", $id);
			$this->view->showAddTask();
		}
		else{
			$this->view->showBadCmd();
		}	
			
	}
}
?>